package com.hiwan.unions.activity.base;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hiwan.unions.R;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.javaScript.AndroidJavaScript;
import com.hiwan.unions.util.AESKit;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.TagUtils;
import com.hiwan.unions.util.Utils;
import com.hiwan.unions.util.interfaces.LoginInterface;
import com.hiwan.unions.view.ProgressWebView;
import com.hiwan.unions.view.PullToRefreshLayout;
import com.hiwan.unions.view.dialog.CallPhoneDialog;
import com.jwenfeng.library.pulltorefresh.ViewStatus;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by llg on 2017/7/6.
 */
public class BaseWebView extends RootActivity implements ProgressWebView.ScrollViewListener, LoginInterface {
    protected boolean shuaxinBoolean = false;
    protected ProgressWebView myWebView;
    private ProgressBar myProgressBar;
    private int currentProgress;
    private boolean isAnimStart = false;
    String phones;
    private AndroidJavaScript javaScript;
    protected String method = "";
    private TextView goBackBtn, goBackBtns, navigationTitleTxt, goBackBtnVideo;
    private LinearLayout layout_title;
    private String action, check;
    private int height = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private FrameLayout mVideoContainer;
    private WebChromeClient.CustomViewCallback mCallBack;
    private CallPhoneDialog dialog;
    private String url = "";

    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 1;


    public void noRunb() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                noWebview();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myWebView.destroy();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initData() {
        local();
    }

    public void local() {
    }

    @Override
    protected void onViewCreated() {
        super.onViewCreated();
        pullToRefreshLayout = findView(R.id.pullToRefreshLayout);
        pullToRefreshLayout.setCanLoadMore(false);
        pullToRefreshLayout.setCancanRefresh(false);
        goBackBtn = findView(R.id.goBackBtnl);
        mVideoContainer = findView(R.id.videoContainer);
        goBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });
        goBackBtns = findView(R.id.goBackBtnslIFE);
        goBackBtns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        layout_title = findView(R.id.layout_title);
        navigationTitleTxt = findView(R.id.navigationTitleTxt);
        myWebView = findView(R.id.myWebView);
        myProgressBar = findView(R.id.myProgressBar);
        goBackBtnVideo = findView(R.id.goBackBtnVideo);
        goBackBtnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                heidCustomView();
            }
        });
        myWebView.setWebViewClient(webviewcilnt);
        myWebView.setWebChromeClient(we);
        javaScript = new AndroidJavaScript(this);
        javaScript.setLoadingListener(this);
        myWebView
                .addJavascriptInterface(javaScript, "Android");
        myProgressBar.setVisibility(View.VISIBLE);
        myProgressBar.setAlpha(1.0f);
        onViewCreateds();
        if (!title) {
            layout_title.setVisibility(View.VISIBLE);
        }
    }

    public void onViewCreateds() {
    }

    @Override
    public void getOperationBtn() {
        super.getOperationBtn();
        if (CheckUtils.isEmpty(check)) {
            return;
        } else {
            if (check.equals("login")) {
                if (CheckUtils.userInfo(this)) {
                    CheckUtils.checkLogin(myWebView, this, action, navigationView.getNavigationTitleTxt().getText().toString(), url);
                }
            } else {
                CheckUtils.checkLogin(myWebView, this, action, navigationView.getNavigationTitleTxt().getText().toString(), url);
            }
        }
    }

    public void getToken() {
        myWebView.loadUrl("javascript:getToken('" + AESKit.decodebase64AndDecrypt(userInfo.getString(ConstantsValues.AUTHTOKEN, ""), ConstantsValues.ASEKIPASSWORD) + "')");
    }

    public PermissionListener Permisslistener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            // 这里的requestCode就是申请时设置的requestCode。
            // 和onActivityResult()的requestCode一样，用来区分多个不同的请求。
            // TODO ...
            Logger.i("sss" + phones);
            if (requestCode == 200) {

                if (dialog == null) {
                    dialog = new CallPhoneDialog(BaseWebView.this);
                    dialog.setOnTextLinstener(new CallPhoneDialog.SumpayDialogListener() {
                        @Override
                        public void nextBtn() {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.CALL");
                            intent.setData(Uri.parse("tel:" + Utils.StringFilter(phones)));
                            startActivity(intent);
                        }
                    });
                }
                dialog.show(phones);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            Utils.tis(deniedPermissions, BaseWebView.this);
        }
    };

    public void call(String phone) {
        phones = phone;
        AndPermission.with(BaseWebView.this)
                .requestCode(200)
                .permission(
                        Manifest.permission.CALL_PHONE
                )
                .callback(Permisslistener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(BaseWebView.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    //h5判断是否执行刷新操作
    public void shuaxinWeb() {
        shuaxinBoolean = true;
    }

    //h5判断是否执行刷新操作
    public void getInfoDetail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                myWebView.quickCallJs("getInfoDetail", userInfo.getString(ConstantsValues.name, ""), userInfo.getString(ConstantsValues.phone, ""));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getToken();
        if (shuaxinBoolean)
            myWebView.reload();
    }

    /**
     * 启动通讯录
     */
    public void callPhoneArres() {
    }

    protected void noWebview() {
        setTitleTxt("网络连接失败");
        setText2("网络连接失败");
        showError();
    }

    protected void showContentView() {
        pullToRefreshLayout.showView(ViewStatus.CONTENT_STATUS);
    }

    /**
     * 网络显示错误
     */
    protected void showError() {
        // 结束刷新
        pullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);
        View error = pullToRefreshLayout.getView(ViewStatus.ERROR_STATUS);
        findView(error, R.id.shuax).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showContentView();
                myWebView.reload();
            }
        });
    }

    public void setText2(String title) {
        navigationTitleTxt.setText(title);
    }

    public WebViewClient webviewcilnt = new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            noWebview();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            myProgressBar.setVisibility(View.VISIBLE);
            myProgressBar.setAlpha(1.0f);
        }

        @TargetApi(android.os.Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (request.isForMainFrame()) { // 或者： if(request.getUrl().toString() .equals(getUrl()))
                noWebview();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Logger.i("url  " + url);
            view.loadUrl("javascript:window.Android.showSource(document.documentElement.innerHTML);");
            view.loadUrl(TagUtils.getJs(url));
            getToken();
            method();
            getDateMethod();
        }
    };

    public void getDateMethod() {

    }

    private void heidCustomView() {
        fullScreen();
        if (mCallBack != null) {
            mCallBack.onCustomViewHidden();
        }
        myWebView.setVisibility(View.VISIBLE);
        navigationView.setVisibility(View.VISIBLE);
        mVideoContainer.removeAllViews();
        goBackBtnVideo.setVisibility(View.GONE);
        mVideoContainer.setVisibility(View.GONE);
        if (!title) {
            layout_title.setVisibility(View.VISIBLE);
        }
    }

    public void method() {
        myWebView.loadUrl("javascript:" + method);
    }

    public WebChromeClient we = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            currentProgress = myProgressBar.getProgress();
            if (newProgress >= 100 && !isAnimStart) {
                // 防止调用多次动画
                isAnimStart = true;
                myProgressBar.setProgress(newProgress);
                // 开启属性动画让进度条平滑消失
                startDismissAnimation(myProgressBar.getProgress(), myProgressBar);
            } else {
                // 开启属性动画让进度条平滑递增
                startProgressAnimation(newProgress, myProgressBar);
            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            fullScreen();
            navigationView.setVisibility(View.GONE);
            myWebView.setVisibility(View.GONE);
            goBackBtnVideo.setVisibility(View.VISIBLE);
            mVideoContainer.setVisibility(View.VISIBLE);
            mVideoContainer.addView(view, 0);
            mCallBack = callback;
            if (!title) {
                layout_title.setVisibility(View.GONE);
            }
            super.onShowCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            heidCustomView();
            super.onHideCustomView();
        }


        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title.contains("404") && !CheckUtils.containsString(title, "authtoken") || title.contains("Error")) {
                noWebview();
            } else {
                setTitleTxt(title);
                setText2(title);
            }
        }

        //配置权限（同样在WebChromeClient中实现）
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        //The undocumented magic method override
        //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*");
            BaseWebView.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg);
        }

        // For Lollipop 5.0+ Devices
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }

            uploadMessage = filePathCallback;

            Intent intent = fileChooserParams.createIntent();
            try {
                startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                return false;
            }
            return true;
        }


    };

    public void startProgressAnimation(int newProgress, ProgressBar myProgressBar) {
        ObjectAnimator animator = ObjectAnimator.ofInt(myProgressBar, "progress", currentProgress, newProgress);
        animator.setDuration(300);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.start();
    }

    /**
     * progressBar消失动画
     */
    public void startDismissAnimation(final int progress, final ProgressBar myProgressBar) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(myProgressBar, "alpha", 1.0f, 0.0f);
        anim.setDuration(1500);  // 动画时长
        anim.setInterpolator(new DecelerateInterpolator());     // 减速
        // 关键, 添加动画进度监听器
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float fraction = valueAnimator.getAnimatedFraction();      // 0.0f ~ 1.0f
                int offset = 100 - progress;
                myProgressBar.setProgress((int) (progress + offset * fraction));
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                // 动画结束
                myProgressBar.setProgress(0);
                myProgressBar.setVisibility(View.GONE);
                isAnimStart = false;
            }
        });
        anim.start();
    }

    @Override
    public void onScrollChanged(ProgressWebView scrollView, int x, int y,
                                int oldx, int oldy) {
        // TODO Auto-generated method stub
        if (title)
            return;
        height = layout_title.getHeight();
        if (y <= 0) {
            layout_title.setBackgroundColor(Color.argb((int) 0, 217, 37, 18));
            navigationTitleTxt.setTextColor(Color.argb((int) 0, 255, 255, 255));
            goBackBtns.setVisibility(View.INVISIBLE);
            goBackBtn.setVisibility(View.VISIBLE);
        } else if (y > 0 && y <= height) {
            //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / height;
            int alpha = (int) (255 * scale);
            layout_title.setBackgroundColor(Color.argb((int) alpha, 217, 37, 18));
            navigationTitleTxt.setTextColor(Color.argb((int) alpha, 255, 255, 255));
            if (y > height / 2) {
                goBackBtns.setVisibility(View.VISIBLE);
                goBackBtn.setVisibility(View.INVISIBLE);
            } else {
                goBackBtns.setVisibility(View.INVISIBLE);
                goBackBtn.setVisibility(View.VISIBLE);
            }
        } else {
            goBackBtns.setVisibility(View.VISIBLE);
            goBackBtn.setVisibility(View.INVISIBLE);
            layout_title.setBackgroundColor(Color.argb((int) 255, 217, 37, 18));
            navigationTitleTxt.setTextColor(Color.argb((int) 255, 255, 255, 255));
        }
    }

    public void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        if (myWebView.getVisibility() == View.GONE) {
            heidCustomView();
        }

    }

    @Override
    public void cityName() {
        super.cityName();


    }

    public void setTitleNa(final String js) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray myJsonObject = new JSONArray(js);
                    if (myJsonObject.length() == 1) {
                        JSONObject jsonObject = JsonUtil.getJSONObject(myJsonObject, 0);
                        check = JsonUtil.getString(jsonObject, "check");
                        action = JsonUtil.getString(jsonObject, "action");
                        url = JsonUtil.getString(jsonObject, "url");
                        if (JsonUtil.getString(jsonObject, "type").equals("menu")) {
                            navigationView.getOperationBtn().setText(JsonUtil.getString(jsonObject, "title"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void TitleTextView(boolean type) {
    }

    @Override
    public void LoginIntent() {
    }

    @Override
    public void getCityInfo() {
        myWebView.quickCallJs("getCityInfo", userInfoC.getString(ConstantsValues.CITYNAMECODE, ""), userInfoC.getString(ConstantsValues.CITYNAME, ""), userInfoC.getString(ConstantsValues.CITYNAMEOneCode, ""), userInfoC.getString(ConstantsValues.CITYNAMEOneCode, ""));
    }

    public void find(String para, int i) {
        hintKbTwo();
        Intent intent = new Intent();
        bundle = new Bundle();
        bundle.putString("method", para);
        bundle.putInt("typeInt", i);
        intent.putExtras(bundle);
        //设置返回数据
        setResult(RESULT_CANCELED, intent);
        //关闭Activity
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case 0:
                if (data != null) {
                    Bundle b = data.getExtras(); //data为B中回传的Intent
                    method = b.getString("method");
                    if (b.containsKey("typeInt")) {
                        int i = b.getInt("typeInt");
                        if (i > 1) {
                            i--;
                            find(method, i);
                        } else {
                            myWebView.loadUrl("javascript:" + method);
                        }
                    } else {
                        myWebView.loadUrl("javascript:" + method);
                    }
                }
                break;
            default:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (requestCode == REQUEST_SELECT_FILE) {
                        if (uploadMessage == null)
                            return;
                        uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                        uploadMessage = null;
                    }
                } else if (requestCode == FILECHOOSER_RESULTCODE) {
                    if (null == mUploadMessage)
                        return;
                    // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
                    // Use RESULT_OK only if you're implementing WebView inside an Activity
                    Uri result = data == null || resultCode != BaseWebView.RESULT_OK ? null : data.getData();
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
                break;
        }
    }
}
